package com.zhkj.txg.module.home.ui

import android.app.Activity
import android.content.Intent
import android.util.Log
import android.view.View
import android.view.ViewTreeObserver
import androidx.core.view.postDelayed
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.home.adapter.HomeBannerAdapter
import com.zhkj.txg.module.home.adapter.MarketCateAdapter
import com.zhkj.txg.module.home.adapter.MarketListAdapter2
import com.zhkj.txg.module.home.entity.BannerEntity
import com.zhkj.txg.module.home.popup.MarketTabPopupWindow
import com.zhkj.txg.module.home.vm.MarketViewModel
import com.zhkj.txg.utils.typeJump
import kotlinx.android.synthetic.main.activity_second_category.*

class SecondCategoryActivity : ViewModelActivity<MarketViewModel>() {

    companion object {
        private val TYPE_MARKET = 0
        private val TYPE_GOODS = 1
        private val TYPE = "type"
        private val ID = "id"
        fun open(activity: Activity, id: Int) {
            val intent = Intent(activity, SecondCategoryActivity::class.java)
                .putExtra(ID, id).putExtra(TYPE, TYPE_MARKET)
            activity.startActivity(intent)
        }

        fun goodsCate(activity: Activity, id: Int) {
            val intent = Intent(activity, SecondCategoryActivity::class.java)
                .putExtra(ID, id).putExtra(TYPE, TYPE_GOODS)
            activity.startActivity(intent)
        }
    }

    // 商品二级分类Adapter
    private val cateAdapter = MarketCateAdapter().apply {
        setOnItemClickListener { _, _, position ->
            appBarSecond.setExpanded(false, false)
            if (position == selectedPosition) return@setOnItemClickListener
            // 设置选中状态
            selectPosition(position)
            // 点击二级分类，滚动到中间
            (rvSecondCategory.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                position, cateWidth / 2
            )
            // 滚动商品列表到对应item
            Log.e("itemClick", "position:$position")
            rvSecondList.scrollToPosition(position)
            // 判断位置是否滚动到位(因为RecyclerView的滚动方法有可能导致滚动不到位，所以需要判断滚动)
            rvSecondList.postDelayed(50) {
                (rvSecondList.layoutManager as LinearLayoutManager).let {
                    val firstPosition = it.findFirstVisibleItemPosition()
                    if (firstPosition != position) {
                        val distance = it.findViewByPosition(firstPosition)
                        rvSecondList.scrollBy(0, (distance?.bottom ?: 0))
                    }
                }
            }
        }
    }

    // 商品列表Adapter
    private val cateListAdapter = MarketListAdapter2()
    private var cateWidth: Int = 0

    // 所有分类的PopupWindow
    private val popupWindow: MarketTabPopupWindow by lazy {
        MarketTabPopupWindow(
            this, viewModel.marketCateLiveData.value?.response?.data?.category ?: mutableListOf()
        ) { position ->
            appBarSecond.setExpanded(false, false)
            if (position == cateAdapter.selectedPosition) return@MarketTabPopupWindow
            // 设置选中状态
            cateAdapter.selectPosition(position)
            // 点击二级分类，滚动到中间
            (rvSecondCategory.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                position, cateWidth / 2
            )
            // 滚动商品列表到对应item
            rvSecondList.scrollToPosition(position)
            // 判断位置是否滚动到位(因为RecyclerView的滚动方法有可能导致滚动不到位，所以需要判断滚动)
            (rvSecondList.layoutManager as LinearLayoutManager).let {
                val firstPosition = it.findFirstVisibleItemPosition()
                if (firstPosition != position) {
                    val distance = it.findViewByPosition(firstPosition)
                    rvSecondList.scrollBy(0, (distance?.bottom ?: 0))
                }
            }
        }
    }

    override fun setViewModel(): MarketViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleSecond
    override val layoutResId: Int = R.layout.activity_second_category

    override fun initUI() {
        // 跳转搜索框
        tvSecondSearch.setOnClickListener {
            if (intent.getIntExtra(TYPE, TYPE_MARKET) == TYPE_MARKET)
                SearchActivity.marketOpen(this, intent.getIntExtra(ID, 0).toLong())
            else SearchActivity.homeOpen(this, intent.getIntExtra(ID, 0).toLong())
        }
        // 弹出所有分类框
        ivSecondCategory.setOnClickListener {
            popupWindow.setSelectedPosition(cateAdapter.selectedPosition)
                .showPopupWindow()
        }
        // 设置二级分类
        with(rvSecondCategory) {
            layoutManager = LinearLayoutManager(this@SecondCategoryActivity, LinearLayoutManager.HORIZONTAL, false)
            adapter = cateAdapter
            viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    cateWidth = rvSecondCategory.measuredWidth
                    viewTreeObserver.removeOnGlobalLayoutListener(this)
                }
            })
        }
        // 设置商品列表
        with(rvSecondList) {
            layoutManager = LinearLayoutManager(this@SecondCategoryActivity)
            adapter = cateListAdapter
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                var isDrag: Boolean = false
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    // 判断是否是拖动导致的视图变化
                    if (!isDrag) return
                    // 判断滚动距离
                    (layoutManager as LinearLayoutManager).let {
                        val firstPosition = it.findFirstVisibleItemPosition()
                        val lastItem = it.findLastCompletelyVisibleItemPosition()
                        val scrollToBottom = rvSecondList.canScrollVertically(-1)
                        val realPosition =
                            if (lastItem == cateAdapter.data.lastIndex && scrollToBottom) cateAdapter.data.lastIndex
                            else firstPosition
                        if (cateAdapter.selectedPosition == realPosition) return
                        // 设置选中状态
                        cateAdapter.selectPosition(realPosition)
                        // 使选中的item出现
                        (rvSecondCategory.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                            realPosition, cateWidth / 2
                        )
                    }
                }

                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    if (newState == RecyclerView.SCROLL_STATE_DRAGGING) isDrag = true
                    else if (newState == RecyclerView.SCROLL_STATE_IDLE) isDrag = false
                }
            })
        }
        cateListAdapter.setEmptyView(R.layout.layout_empty_data)
        bannerSecond.layoutParams.height = (ScreenUtil.getScreenWidth(this) * 0.75).toInt()
        bannerSecond.addBannerLifecycleObserver(this).setAdapter(HomeBannerAdapter(this))
            .setOnBannerListener { data, _ ->
                (data as? BannerEntity)?.let {
                    typeJump(this, it.jumpType ?: 0, it.params, it.title)
                }
            }
    }

    override fun initViewModel() {
        // 页面数据观察者
        viewModel.marketCateLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) it.response?.data?.let { data ->
                // 设置轮播图
                bannerSecond.adapter.setDatas(data.banner)
                bannerSecond.adapter.notifyDataSetChanged()
                bannerSecond.start()
                // 设置二级分类列表
                if (data.category.isNotEmpty()) {
                    viewSecondCate.visibility = View.VISIBLE
                    cateAdapter.setNewData(data.category)
                    rvSecondCategory.scrollToPosition(0)
                } else viewSecondCate.visibility = View.GONE
                // 设置商品列表
                cateListAdapter.setNewData(data.list)
                rvSecondList.scrollToPosition(0)
            }
        })
    }

    override fun initData() {
        val catId = intent.getIntExtra(ID, 0)
        val type = intent.getIntExtra(TYPE, TYPE_MARKET)
        if (type == TYPE_MARKET) viewModel.marketCate(AccountManager.getToken(), catId)
        else viewModel.secondCate(AccountManager.getToken(), catId)
    }
}